import java.util.*;
import java.rmi.RemoteException;

public class Race
{
    private Date _startTime;
    private Date _stopTime;
    private Vector _lapTimes;
    
    public Race()
    {
        initialize();
    }
    
    public void start()
    {
        getStartTime().setTime(System.currentTimeMillis());
    }
    
    public void stop()
    {
        getStopTime().setTime(System.currentTimeMillis());
        getLapTimes().trimToSize();
    }
    
    public void save()
    {
        
    }
    
    public Date recordLapTime(int racerNumber)
    {
        Date splitTime = new Date();
        splitTime.setTime(System.currentTimeMillis() - getStartTime().getTime());
        int currentLap = getLapCount(racerNumber) + 1;
        
        LapTime newLapTime = new LapTime(racerNumber,currentLap,splitTime);
        getLapTimes().addElement(newLapTime);
        return splitTime;
    }
    
    public String serializeResults()
    {
        StringBuffer serializedResults = new StringBuffer();
        for(int i=0;i < getLapTimes().size(); i++)
        {
            LapTime lapTime =  (LapTime)getLapTimes().elementAt(i);
            serializedResults.append(lapTime.getRacerNumber());
            serializedResults.append(";");
            serializedResults.append(lapTime.getLapNumber());
            serializedResults.append(";");
            serializedResults.append(Utils.extractTimeString(lapTime.getTime()));
            serializedResults.append(";");
            
            serializedResults.append("|");
        }
       
        return serializedResults.toString();
    }
    
    private int getLapCount(int racerNumber)
    {
        int lapCount =0;
        for(int i=0;i < getLapTimes().size(); i++)
        {
            LapTime lapTime =  (LapTime)getLapTimes().elementAt(i);
            if(lapTime.getRacerNumber() == racerNumber)
                lapCount++;
        }
        return lapCount;
    }
    
    private void initialize()
    {
        _startTime = new Date();
        _stopTime = new Date();
        _lapTimes = new Vector();
    }
    
    private void deInitialize()
    {
        _startTime = null;
        _stopTime = null;
        _lapTimes = null;
    }
    
    public Date getStartTime()
    {
        return _startTime;
    }
    
    public Date getStopTime()
    {
        return _stopTime;
    }
    
    public Vector getLapTimes()
    {
        return _lapTimes;
    }
}
